package br.com.eSink.dao;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class Key {

    KeyDao keyDao;
    String encrypted, name;

    //RECEBE CHAVE DO DISPOSITIVO ANDROID
    public Key(String key, String name, Statement stmt, Connection con) throws SQLException {
        this.name = name;
        keyDao = new KeyDao(con);
        encrypted = generateHash(key, "MD5");
    }

    public void verifyConnection() throws SQLException {
        if (!keyDao.searchKey(encrypted)) {
            System.out.println("Primeira conexão.");
            keyDao.createColumn(encrypted);
            keyDao.addKey(encrypted, name);
        }
    }

    public static String generateHash(String sentence, String alg) {
        try {
            MessageDigest md = MessageDigest.getInstance(alg);
            md.update(sentence.getBytes());

            StringBuilder s = new StringBuilder();
            for (int i = 0; i < md.digest().length; i++) {
                int high = ((md.digest()[i] >> 4) & 0xf) << 4;
                int low = md.digest()[i] & 0xf;
                if (high == 0) {
                    s.append('0');
                }
                s.append(Integer.toHexString(high | low));
            }
            return s.toString();

        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
//    public static void main(String args[]) throws SQLException {
//        ConexaoDatabase conexaoDatabase = new ConexaoDatabase();
//        Connection con;
//        con = conexaoDatabase.openConnection("src/br/com/esink/database/eSinkDatabase", "eSink", "");
//        Statement stmt = con.createStatement();
//        Chave chave = new Chave("Biscoito", "Thyago", stmt, con);
//        chave.verificarConexao();
//        conexaoDatabase.closeConnection(con);
//    }    
}
